<template>
    <van-pull-refresh 
        :disabled="!enableRefresh"
        v-model="refreshing" 
        success-text="刷新成功"
        @refresh="onRefresh"
    >
        <van-list
            v-model:loading="loading"
            :finished="finished"
            :immediate-check="autoLoad"
            finished-text="没有更多了"
            @load="onLoad"
        >
            <template #loading>
                <van-loading :color="loadingColor" type="spinner">{{ loadingText }}</van-loading>
            </template>
            <slot></slot>
        </van-list>
    </van-pull-refresh>
</template>

<script>
import { ref, onBeforeUnmount, inject } from 'vue'
import { PullRefresh as VanPullRefresh, List as VanList, Loading as VanLoading } from 'vant'
export default {
    name: 'LoadMore',
    components: {
        VanPullRefresh,
        VanList,
        VanLoading
    },
    emits: ['refresh', 'load'],
    props: {
        // 是否允许上拉加载
        enableLoad: {
            type: Boolean,
            default: true
        },
        // 是否允许下拉刷新
        enableRefresh: {
            type: Boolean,
            default: true
        },
        finishedText: {
            type: String,
            default: '没有更多了'
        },
        // 是否自动加载
        autoLoad: {
            type: Boolean,
            default: false
        },
        // 加载提示文本
        loadingText: {
            type: String,
            default: '加载中...'
        }
    },
    setup(props, { emit }) {
        const loadingColor = inject('themeColor')
        const refreshing = ref(false)
        const loading = ref(false)
        const finished = ref(false)

        const stopRefresh = () => {
            refreshing.value = false
        }
        
        const startLoad = () => {
            loading.value = true
        }

        const stopLoad = () => {
            loading.value = false
        }

        const completeLoad = () => {
            finished.value = true
        }
        
        const isComplete = () => {            
            return !!finished.value
        }

        const reset = () => {
            loading.value = false
            refreshing.value = false
            finished.value = false
        }

        const onRefresh = () => {
            if (props.enableRefresh) {
                reset()
                emit('refresh')
            }
        }

        const onLoad = () => {
            if (props.enableLoad) {
                emit('load')
            }
        }

        onBeforeUnmount(() => {
            reset()
        })

        return {
            refreshing,
            loading,
            loadingColor,
            finished,
            onRefresh,
            onLoad,
            completeLoad,
            stopRefresh,
            startLoad,
            stopLoad,
            isComplete,
            reset
        }
    }
}
</script>